//
//  KNewsController.m
//  Keping
//
//  Created by a on 2017/9/15.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KNewsController.h"

#import "KNewsGeneralController.h"
#import "KNewsPersonalController.h"
#import "KNewsFeedbackController.h"
#import "KNewsGeneralDetailController.h"
#import "KMenuView.h"
#import "NewsPersonalRequest.h"
#import "KNewStarModel.h"
#import "KPersonalModel.h"
#import "KNewsPersonalDetailController.h"
#import "KGeneralCommentsController.h"


@interface KNewsController ()<UIScrollViewDelegate>
/**
 头部试图
 */
@property(nonatomic,weak)UIView*headerView;
/**
 内容
 */
@property(nonatomic,weak)UIScrollView*contentScrollView;
@property (nonatomic, strong)KNewStarModel *starModel;
@property (nonatomic, strong)UILabel *redPoint;
@end

@implementation KNewsController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getData];
}

- (void)getData {
    [super getData];
    WEAKSELF
    [self showLoading];
    NewsStarRequest *request = [[NewsStarRequest alloc] init];
    [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        NSDictionary *dict = request.responseObject;
        NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
        if (status == 200) {
            weakSelf.starModel = [KNewStarModel modelWithDictionary:[dict objectForKey:@"bbsTopicStateView"]];
            if (weakSelf.starModel.myReplyNumber > 0 || weakSelf.starModel.personaNoticeNumber > 0) {
                weakSelf.navigationItem.rightBarButtonItem=[UIBarButtonItem itemWithImage:@"cctv_enum_red" withName:nil target:self action:@selector(clickRightItem)];
            } else {
                weakSelf.navigationItem.rightBarButtonItem=[UIBarButtonItem itemWithImage:@"cctv_enum" withName:nil target:self action:@selector(clickRightItem)];
            }
        } else {
            weakSelf.navigationItem.rightBarButtonItem=[UIBarButtonItem itemWithImage:@"cctv_enum" withName:nil target:self action:@selector(clickRightItem)];
            [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:status];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        [weakSelf showError:request.error];
    }];
}

- (void)cleanNewStar:(NSInteger)index {
    WEAKSELF
    CleanNewsStarRequest *request = [[CleanNewsStarRequest alloc] init];
    request.params = @{@"type":@(index)};
    [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        NSDictionary *dict = request.responseObject;
        NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
        if (status == 200) {
            if (index == 0) {
                weakSelf.starModel.myReplyNumber = 0;
            } else {
                weakSelf.starModel.personaNoticeNumber = 0;
            }
            
            if (weakSelf.starModel.myReplyNumber > 0 || weakSelf.starModel.personaNoticeNumber > 0) {
                weakSelf.navigationItem.rightBarButtonItem=[UIBarButtonItem itemWithImage:@"cctv_enum_red" withName:nil target:self action:@selector(clickRightItem)];
            } else {
                weakSelf.navigationItem.rightBarButtonItem=[UIBarButtonItem itemWithImage:@"cctv_enum" withName:nil target:self action:@selector(clickRightItem)];
            }
            
        } else {
            [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:status];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf showError:request.error];
    }];
}

- (void)getNewPersonal {
    WEAKSELF
    [self showLoading];
    NewsPersonalDetailRequest *request = [[NewsPersonalDetailRequest alloc] initWithNewPersonalId:self.starModel.personaNoticeNumberId];
    [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        NSDictionary *dict = request.responseObject;
        NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
        if (status == 200) {
            glRecommendViews *recommend = [glRecommendViews modelWithDictionary:[dict objectForKey:@"glRecommendView"]];
            KNewsPersonalDetailController *vc = [[KNewsPersonalDetailController alloc] initWithNibName:[KNewsPersonalDetailController className] bundle:nil];
            vc.recommendView = recommend;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        } else {
            [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:status];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        [weakSelf showError:request.error];
    }];
}

-(void)setUI
{
    self.navigationItem.title=@"News";
    
    //头部滚动视图
    UIView*headerView=[[UIView alloc]initWithFrame:CGRectMake(0,0, self.view.width, K_FactorH(45))];
    [self.view addSubview:headerView];
    self.headerView=headerView;
    
    //centerScroll
    UIScrollView*contentScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(headerView.frame), self.view.width,self.view.height-CGRectGetMaxY(headerView.frame))];
    contentScrollView.backgroundColor=[UIColor whiteColor];
    contentScrollView.pagingEnabled=YES;
    contentScrollView.showsVerticalScrollIndicator=NO;
    contentScrollView.showsHorizontalScrollIndicator=NO;
    contentScrollView.delegate=self;
    [self.view addSubview:contentScrollView];
    self.contentScrollView=contentScrollView;
    
    // 添加子控制器
    [self setupChildVc];
    
    // 添加标题
    [self setupTitle];
    
    // 默认显示第0个子控制器
    [self scrollViewDidEndScrollingAnimation:self.contentScrollView];
}
-(void)clickRightItem
{
    KMenuView *mennView = [[KMenuView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-133-20, 64+5, 133, 177.5) itemDictArray:@[@{@"title":@"My reply",@"Num":[NSString stringWithFormat:@"%ld",(long)self.starModel.myReplyNumber]},@{@"title":@"Personal notice",@"Num":[NSString stringWithFormat:@"%ld",(long)self.starModel.personaNoticeNumber]},@{@"title":@"Feedback",@"Num":@"0"}]];
    WEAKSELF
    [mennView showWithDidSelectRowOfIndexPathBlock:^(NSIndexPath *indexPath) {
        if (indexPath.row == 0) {
            if (weakSelf.starModel.myReplyNumber == 0) {
                return;
            }
            [weakSelf cleanNewStar:indexPath.row];
            KGeneralCommentsController *vc=[KGeneralCommentsController new];
            vc.bbsPostID = weakSelf.starModel.myReplyNumberId;
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 1){
            if (weakSelf.starModel.personaNoticeNumber == 0) {
                return;
            }
            [weakSelf cleanNewStar:indexPath.row];
            [weakSelf getNewPersonal];
        }else if (indexPath.row == 2){
            UIButton *btn;
            btn = [weakSelf.headerView viewWithTag:102];
            [weakSelf clickHeadBtn:btn];
        }
    }];
}
- (void)setupChildVc
{
    
    KNewsGeneralController *GeneralVC = [[KNewsGeneralController alloc] init];
    GeneralVC.title=@"General";
    [self addChildViewController:GeneralVC];
    
    KNewsPersonalController *PersonalVC = [[KNewsPersonalController alloc] init];
    PersonalVC.title=@"Personal";
    [self addChildViewController:PersonalVC];
    
    KNewsFeedbackController *FeedbackVC = [[KNewsFeedbackController alloc] init];
    FeedbackVC.title=@"Feedback";
    [self addChildViewController:FeedbackVC];
}
/**
 * 添加标题
 */
- (void)setupTitle
{
    // 定义临时变量
    CGFloat btnW = self.view.width/self.childViewControllers.count;
    CGFloat btnY = 0;
    CGFloat btnH = self.headerView.frame.size.height;
    
    // 添加按钮
    for (NSInteger i = 0; i<self.childViewControllers.count; i++) {
        UIButton *btn = [[UIButton alloc] init];
        [btn setTitle:[self.childViewControllers[i] title] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor colorWithHexString:@"#734ffb"] forState:UIControlStateSelected];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.backgroundColor=[UIColor clearColor];
        [btn setBackgroundColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [btn setBackgroundColor:[UIColor colorWithHexString:@"#734ffb"] forState:UIControlStateNormal];
        CGFloat btnX = i * btnW;
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        [btn addTarget:self action:@selector(clickHeadBtn:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = i + 100;
        [self.headerView addSubview:btn];
        if (i != 0 && i == self.selectIndex) {
            [self performSelector:@selector(clickHeadBtn:) withObject:btn];
        }
    }
    // 设置contentSize
    self.contentScrollView.contentSize = CGSizeMake(self.childViewControllers.count * App_Frame_Width, 0);
}
/**
 * 监听顶部label点击
 */
- (void)clickHeadBtn:(UIButton *)btn
{
    // 取出被点击label的索引
    NSInteger index = btn.tag - 100;
    
    // 让底部的内容scrollView滚动到对应位置
    CGPoint offset = self.contentScrollView.contentOffset;
    offset.x = index * self.contentScrollView.frame.size.width;
    [self.contentScrollView setContentOffset:offset animated:YES];
}

#pragma mark - <UIScrollViewDelegate>
/**
 * scrollView结束了滚动动画以后就会调用这个方法（比如- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated;方法执行的动画完毕后）
 */
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    // 一些临时变量
    CGFloat width = scrollView.frame.size.width;
    CGFloat height = scrollView.frame.size.height;
    CGFloat offsetX = scrollView.contentOffset.x;
    
    // 当前位置需要显示的控制器的索引
    NSInteger index = offsetX / width;
    
    // 让对应的顶部标题选中
    UIButton *btn = self.headerView.subviews[index];
    btn.selected=YES;
    //    CGPoint titleOffset = self.titleScrollView.contentOffset;
    // 让其他按钮回到最初的状态
    for (UIButton *otherBtn in self.headerView.subviews) {
        if ([otherBtn isKindOfClass:[UIButton class]]) {
            if (otherBtn != btn) otherBtn.selected=NO;
        }
        
    }
    // 取出需要显示的控制器
    UIViewController *willShowVc = self.childViewControllers[index];
    
    // 如果当前位置的位置已经显示过了，就直接返回
    if ([willShowVc isViewLoaded]) return;
    
    // 添加控制器的view到contentScrollView中;
    willShowVc.view.frame = CGRectMake(offsetX,0, width, height);
    [scrollView addSubview:willShowVc.view];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
}
/**
 * 手指松开scrollView后，scrollView停止减速完毕就会调用这个
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self scrollViewDidEndScrollingAnimation:scrollView];
}

@end
